package org.apogee.mil.server;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apogee.mil.server.database.DatabaseDriver;
import org.apogee.mil.server.database.DatabaseDriver.TableStatus;

public class FileUploadHandler extends HttpServlet{

	private static Logger logger = Logger.getLogger(FileUploadHandler.class);

	private String ok = "";
	private boolean finished = false;
	private String key = "filename=";
	private DatabaseDriver dbDriver = new DatabaseDriver();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		dbDriver.initialize();

		finished = false;

		logger.info("Inside FileuploadHandler");

		ServletInputStream stream = req.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(stream);

		StringBuilder builder = new StringBuilder();

		while(bis.read() != -1) {
			byte[] bytes = new byte[req.getContentLength()];
			bis.read(bytes);
			builder.append(new String(bytes));
		}

		String[] questions = builder.toString().split("\n");

		String test = "";

		for (String s : questions) {
			int fileNameIndex = s.indexOf(key);

			if (fileNameIndex != -1) {
				test = s.substring(fileNameIndex + key.length() + 1, s.lastIndexOf("."));
				break;
			}
		}

		TableStatus status = dbDriver.createDatabase(test);

		logger.info("Test name= " + test + " Added: " + status);


		boolean started = false;
		int lineNumber = 0;
		int currentVolume = 0;


		if (status == TableStatus.ERROR || status == TableStatus.NOT_ADDED) {
			ok = "Questions not added";
			finished = true;
			return;
		}

		logger.info("Number of questions: " + questions.length);
		for (String s : questions) {
			try {
				if (s.startsWith("[")) {
					started = true;
				}

				if (started) {
					lineNumber++;
					if (s.toLowerCase().startsWith("[volume")) {
						currentVolume++;
					}

					if (s.startsWith("[")) {
						continue;
					} else if (s.trim().equals("")) {
						continue;
					}

					String[] question = s.split(":");

					if (question.length == 2) {
						dbDriver.addQuestion(test, question[0], question[1], "None","None", "None", 1, currentVolume, "R");
					}
					else if (question.length == 6) {
						dbDriver.addQuestion(test, question[0], question[1], question[2], question[3], question[4], Integer.parseInt(question[5]), currentVolume, "T");
					}
					else {
						logger.info("Not enough Parameters Line " + lineNumber + " Question: " + s);
					}

				}


			} catch (Exception ex) {
				continue;
			}
		}
		currentVolume = 0;
		ok = "Questions Successfully Uploaded";
		finished = true;

	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {

		int count = 0;

		while (finished == false) { count++; }
		finished = false;

		resp.setContentType("text/html");

		String write = "<p>" + ok + "<p>";

		logger.info("In doGet writing: " + write + " count: " + count);

		PrintWriter writer = resp.getWriter();
		writer.write(write);
		writer.close();
	}
}
